package model

import (
	"bytes"
	"crypto/ecdsa"
	"encoding/json"
	"encoding/pem"
	"fmt"
	"github.com/emmansun/gmsm/smx509"
	"io"
	"log"
	"os"
)

const (
	Certificate = 2000 //请求消息
	SPA         = 2001 // 发送单包消息
)

// Device 用于客户端与零信任网关通讯,
type Device struct {
	ID          uint
	Token       string
	Factory     string
	MessageType int
	Data        []byte
}

// PemExcitePublic 网关验证本地是否有对应设备的公钥
func (device *Device) PemExcitePublic() bool {
	_, err := os.Stat("./key/" + device.Token + ".pem")
	if err == nil {
		return true
	}
	return false
}

func (device *Device) ReadPublicFromToken(pemStr string) *ecdsa.PublicKey {
	//fmt.Println("pemStr", pemStr)
	decode2, _ := pem.Decode([]byte(pemStr))
	//fmt.Println("11", []byte(pemStr))
	//fmt.Println(hex.DecodeString(pemStr))
	key, err := smx509.ParsePKIXPublicKey(decode2.Bytes)
	if err != nil {
		panic(err)
	}
	pu := key.(*ecdsa.PublicKey)
	return pu
}

func (device *Device) ReadPublicFromToken2() *ecdsa.PublicKey {
	//pubF, err := os.Open("./key/" + device.Token + ".pem")
	pubF, err := os.Open("./key/public.pem")
	defer pubF.Close()
	if err != nil {
		panic(err)
	}
	//解析公钥
	b2 := new(bytes.Buffer)
	io.Copy(b2, pubF)
	decode2, _ := pem.Decode(b2.Bytes())
	fmt.Println("ReadPublicFromToken2", b2.Bytes())
	key, err := smx509.ParsePKIXPublicKey(decode2.Bytes)
	if err != nil {
		panic(err)
	}
	pu := key.(*ecdsa.PublicKey)
	return pu
}

func (device *Device) ToBytes() []byte {
	marshal, err := json.Marshal(device)
	if err != nil {
		log.Println(err)
	}
	return marshal
}

func (de *Device) ToDeviceInfo() *DeviceInfo {
	newd := new(DeviceInfo)
	newd.ID = de.ID
	newd.Token = de.Token
	newd.Factory = de.Factory
	return newd
}

func (de *Device) ToKeyGenerateMessage(ip string) *KeyGenerateMessage {
	newd := new(KeyGenerateMessage)
	newd.ID = de.ID
	newd.Token = de.Token
	newd.IPADDR = ip
	return newd
}
